package cn.itcast.reggie.filter;

import cn.itcast.reggie.common.BaseContext;
import cn.itcast.reggie.common.R;
import com.alibaba.fastjson.JSON;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class AuthorizationFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取请求url
        String url = request.getRequestURI();
        //2.判断请求url是否是登录相关资源
        boolean b = isLoginResource(url);
        if(b) {
            //是
            filterChain.doFilter(request,response);
            return;
        }

        //判断session中是否有employee，管理员登录
        HttpSession session = request.getSession();
        Long employeeId = (Long) session.getAttribute("employee");
        if(employeeId != null) {
            BaseContext.setCurrentId(employeeId);
            filterChain.doFilter(request,response);
            return;
        }

        //判断session中是否有user，用户登录
        Long userId = (Long) session.getAttribute("user");
        if(userId != null) {
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        //拦截
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));


    }

    //判断请求url是否匹配下面地址
    private boolean isLoginResource(String url) {
        String[] urls = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/user/sendMsg",
                "/user/login",
                };
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String s : urls) {
            boolean match = antPathMatcher.match(s, url);
            if(match) {
                return true;
            }
        }

        return false;
    }
}
